import 'dart:async';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mziot/app/data/product_group_entity.dart';
import 'package:mziot/app/modules/devices/device_provider.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/tools.dart';

class AddDeviceController extends GetxController {
  DeviceProvider provider = DeviceProvider();
  final devicesGroup = <ProductGroupEntity>[].obs;
  final blueDevices = <DiscoveredDevice>[].obs;
  final isFilter = true.obs;
  StreamSubscription? scanListen;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() async {
    super.onReady();
    fetchProductList();
    final enable = await MPermission.instance.bluetooth();
    if (!enable) {
      return;
    }

    Future.delayed(Duration(seconds: 1), () {
      scanDevices('MZ_MZ');
    });
  }

  void scanDevices(String name, {bool isFilter = true}) async {
    BlueService.share.isAdd = true;
    await BlueService.share.disConnectDevice();
    BlueService.share.isAll = true;
    blueDevices.value = [];
    scanListen?.cancel();
    scanListen = null;
    BlueService.share.scanDevices().then((value) {
      scanListen = value?.listen((event) {
        final devices = BlueService.share.filterDevices(
          event,
          blueDevices.value,
        );

        blueDevices.value = devices;
      });
    });
  }

  void fetchProductList() {
    provider.takeProductList().then((value) {
      if (value.isSuccess) {
        devicesGroup.value = value.data!;
      }
    });
  }

  @override
  void onClose() async {
    EasyLoading.dismiss();
    scanListen?.cancel();
    scanListen = null;
    await BlueService.share.stopScan();
  }
}
